package com.yanzu.module.member.service.deviceinfo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yanzu.framework.common.pojo.PageResult;
import com.yanzu.module.member.controller.admin.deviceinfo.vo.*;
import com.yanzu.module.member.convert.deviceinfo.DeviceInfoConvert;
import com.yanzu.module.member.dal.dataobject.deviceinfo.DeviceInfoDO;
import com.yanzu.module.member.dal.dataobject.deviceinfo.DeviceNumTabDO;
import com.yanzu.module.member.dal.mysql.deviceinfo.DeviceInfoMapper;
import com.yanzu.module.member.dal.mysql.deviceinfo.DeviceNumTabMapper;
import com.yanzu.module.member.enums.AppEnum;
import com.yanzu.module.member.service.iot.IotDeviceService;
import com.yanzu.module.member.service.iot.SmyooService;
import com.yanzu.module.member.service.iot.TTLockService;
import com.yanzu.module.member.service.iot.device.IotDeviceSetAutoLockReqVO;
import com.yanzu.module.member.service.storeinfo.StoreInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static com.yanzu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yanzu.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.yanzu.framework.web.core.util.WebFrameworkUtils.getLoginUserType;
import static com.yanzu.module.member.enums.ErrorCodeConstants.*;

/**
 * 设备管理 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DeviceInfoServiceImpl implements DeviceInfoService {

    @Resource
    private DeviceInfoMapper deviceInfoMapper;

    @Resource
    private DeviceNumTabMapper deviceNumTabMapper;

    @Resource
    private IotDeviceService iotDeviceService;

    @Resource
    private TTLockService ttLockService;
    @Resource
    private StoreInfoService storeInfoService;

    @Resource
    private SmyooService smyooService;

    @Override
    @Transactional
    public void createDeviceInfo(DeviceInfoCreateReqVO createReqVO) {
        //新增的设备不能存在
        int i = deviceInfoMapper.countBySN(createReqVO.getDeviceSn());
        if (i > 0) {
            throw exception(DEVICE_DATA_EXISTS_ERROR);
        }
        // 插入
        DeviceInfoDO deviceInfo = DeviceInfoConvert.INSTANCE.convert(createReqVO);
        if (createReqVO.getType().compareTo(AppEnum.device_type.LOCK.getValue()) == 0) {
            //通通锁
            String key = ttLockService.getKey(Integer.valueOf(createReqVO.getDeviceSn()), createReqVO.getStoreId());
            deviceInfo.setDeviceData(key);
        } else if (createReqVO.getType().compareTo(AppEnum.device_type.GATEWAY.getValue()) != 0) {
            //闪优设备
            String queryMcuId = smyooService.queryMcuId(createReqVO.getStoreId(), createReqVO.getDeviceSn());
            deviceInfo.setDeviceData(queryMcuId);
        }
        deviceInfoMapper.insert(deviceInfo);
    }



    @Override
    public DeviceNumTabDO getDeviceNum(Long configurationId, String deviceType) {
        QueryWrapper<DeviceNumTabDO> deviceNumDOQueryWrapper = new QueryWrapper<>();
        deviceNumDOQueryWrapper.eq("configuration_id", configurationId);
        deviceNumDOQueryWrapper.eq("device_type", deviceType);
        return deviceNumTabMapper.selectOne(deviceNumDOQueryWrapper);
    }



    @Override
    @Transactional
    public void deleteDeviceInfo(Long id) {
        DeviceInfoDO deviceInfoDO = deviceInfoMapper.selectById(id);
        //只能操作自己的设备
        if (!ObjectUtils.isEmpty(deviceInfoDO) && deviceInfoDO.getCreator().equals(String.valueOf(getLoginUserId()))) {
            // 删除
            deviceInfoMapper.deleteById(id);
        }
    }

    private void validateDeviceInfoExists(Long id) {
        if (deviceInfoMapper.selectById(id) == null) {
            throw exception(DATA_NOT_EXISTS);
        }
    }

    @Override
    public DeviceInfoDO getDeviceInfo(Long id) {
        return deviceInfoMapper.selectById(id);
    }

    @Override
    public List<DeviceInfoDO> getDeviceInfoList(Collection<Long> ids) {
        return deviceInfoMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DeviceInfoRespVO> getDeviceInfoPage(DeviceInfoPageReqVO reqVO, boolean isAdmin) {
        //检查权限
        storeInfoService.checkPermisson(null, null, getLoginUserType(), AppEnum.member_user_type.ADMIN.getValue());
        IPage<DeviceInfoRespVO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        deviceInfoMapper.getDeviceInfoPage(page, reqVO, getLoginUserId(), isAdmin);
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public List<DeviceInfoDO> getDeviceInfoList(DeviceInfoExportReqVO exportReqVO) {
        return deviceInfoMapper.selectList(exportReqVO);
    }

    @Override
    @Transactional
    public void bind(DeviceInfoBindReqVO reqVO) {
        //如果设备已经被绑定了， 就更新绑定关系
        DeviceInfoDO deviceInfoDO = deviceInfoMapper.selectById(reqVO.getDeviceId());
        if (ObjectUtils.isEmpty(deviceInfoDO)) {
            throw exception(DATA_NOT_EXISTS);
        }
        deviceInfoMapper.updateBindInfo(deviceInfoDO.getDeviceId(), reqVO.getStoreId(), reqVO.getRoomId());
    }

    @Override
    public void setLockAutoLock(DeviceInfoSetAutoLockReqVO reqVO) {
        DeviceInfoDO deviceInfoDO = deviceInfoMapper.selectById(reqVO.getDeviceId());
        //只能操作自己的设备
        if (!ObjectUtils.isEmpty(deviceInfoDO) && deviceInfoDO.getCreator().equals(String.valueOf(getLoginUserId()))) {
            IotDeviceSetAutoLockReqVO vo = new IotDeviceSetAutoLockReqVO();
            vo.setSecend(reqVO.getSecend());
            ttLockService.setLockAutoLock(vo, deviceInfoDO.getDeviceSn(), deviceInfoDO.getStoreId());
        }
    }

    @Override
    public void control(DeviceControlReqVO reqVO) {
        DeviceInfoDO deviceInfoDO = deviceInfoMapper.selectById(reqVO.getDeviceId());
        //只能操作自己的设备
        if (!ObjectUtils.isEmpty(deviceInfoDO) && deviceInfoDO.getCreator().equals(String.valueOf(getLoginUserId()))) {
            //1=门禁 2=空开 3=云喇叭 4=灯具 5=密码锁 6=网关 7=插座
            switch (deviceInfoDO.getType()) {
                case 1:
                    smyooService.opSwitch(deviceInfoDO.getStoreId(), deviceInfoDO.getDeviceData(), 0);
                    //1秒后再打开
                    Timer timer = new Timer();
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            smyooService.opSwitch(deviceInfoDO.getStoreId(), deviceInfoDO.getDeviceData(), 1);
                        }
                    };
                    // 定时器延时1秒（1000毫秒）后执行任务
                    timer.schedule(task, 1000);
                    break;
                case 2:
                case 4:
                case 7:
                    smyooService.opSwitch(deviceInfoDO.getStoreId(), deviceInfoDO.getDeviceData(), reqVO.getCmd().equals("on") ? 1 : 0);
                    break;
                case 5:
                    ttLockService.unlock(Integer.valueOf(deviceInfoDO.getDeviceSn()), deviceInfoDO.getStoreId());
                    break;
                case 3:
                    smyooService.runSound(deviceInfoDO.getStoreId(), deviceInfoDO.getDeviceData(), "1", 6);
                    break;
            }
        }
    }
}
